import { useQuery } from "@apollo/client";
import { connectFactory, useAppContext } from "@/utils/contextFactory";
import { GET_USER } from "@/graphql/user";
import type { IUser } from "@/utils/types";
import React from "react";
import { useLocation, useNavigate } from "react-router-dom";

const KEY = "userInfo";
const DEFAULT_VALUE = {};

export const useUserContext = () => useAppContext<IUser>(KEY);
export const connect = connectFactory(KEY, DEFAULT_VALUE);

export const useGetUser = () => {
  const { store, setStore } = useUserContext();
  const location = useLocation();
  const nav = useNavigate();
  // console.log("useGetUser-store", store);
  const query = useQuery<{ getUserInfo: IUser }>(GET_USER, {
    // 该方法已经弃用
    // onCompleted: (data) => {
    //     console.log('data',data);
    //   if (data) {
    //     console.log('data.getUserInfo',data.getUserInfo);
    //     if (data.getUserInfo) {
    //       const { id, name, tel } = data.getUserInfo;
    //       setStore({ id, name, tel });
    //       console.log("onCompleted-data", data);
    //     }
    //     if (window.location.pathname !== "/login") {
    //       window.location.href = "/login";
    //     }
    //   }
    // },
    // onError: () => {
    //     console.log('onError');
    //   if (window.location.pathname !== "/login")
    //     window.location.href = "/login";
    // },
  });
  React.useEffect(() => {
    if (query.data) {
      if (query.data.getUserInfo) {
        const { id, name, tel, desc, avatar } = query.data.getUserInfo;
        setStore({ id, name, tel, desc, avatar,refetchHandler: query.refetch });
        // console.log("data", query.data);
        if (location.pathname.startsWith("/login")) {
          nav(`${location.pathname}`);
        }
        return;
      }
      setStore({ refetchHandler: query.refetch });
      //   之前因为UserInfo在最外层，无法使用react router
      //   if (window.location.pathname !== "/login")
      //     window.location.href = `/login?orgUrl=${window.location.pathname}`;
      if (location.pathname !== "/login") {
        nav(`/login?orgUrl=${location.pathname}`);
      }
    }
    if (query.error) {
      setStore({ refetchHandler: query.refetch });
      console.error(query.error.message);
      //   if (window.location.pathname !== "/login")
      //     window.location.href = `/login?orgUrl=${window.location.pathname}`;
      if (location.pathname !== "/login")
        nav(`/login?orgUrl=${location.pathname}`);
    }
  // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [query.data || query.error]);

  return { loading: query.loading, refetch: query.refetch };
};
